<template>
  <div ref="box">
    <b-table
      ref="table"
      :columns="columns"
      :out-loading="loading"
      :request="loadData"
      :del-func="delFunc"
      bordered
      class="bgFFF"
      :scroll="{ x: 2500 }"
      :export-config="{ use: true, select: '物资用量确认单用量明细', all: '物资用量确认单用量明细' }"
      :disabled="disabled"
    >
      <template v-if="state !== 3" slot="prefix">
        <a-button type="primary" :loading="loading" @click="openDialog()"> 添加行 </a-button>
      </template>
      <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
      <template
        v-for="col in [
          'number',
          'lastSize',
          'contractPrice',
          'taxRatePercentName',
          'taxAmount',
          'includeTaxAmount',
          'includeTaxTotalAmount',
          'deliveryDate',
          'quantity',
          'remark'
        ]"
        :slot="col"
        slot-scope="text, record"
      >
        <div :key="col">
          <template v-if="state !== 3">
            <span v-if="col === 'taxRatePercentName'" class="ant-form-item-children requiredFormItem">
              <a-select
                v-model="record['taxRatePercentId']"
                :getPopupContainer="() => $refs.box"
                @change="(e) => handleChange(e, record, col)"
              >
                <a-select-option v-for="item in rateArr" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </span>
            <a-date-picker
              v-else-if="col === 'deliveryDate'"
              v-model="record[col]"
              value-format="YYYY-MM-DD"
              class="requiredFormItem"
              @change="handleChange($event, record, col)"
            />
            <BaseInputNumber
              v-else-if="col === 'quantity'"
              v-model="record[col]"
              :precision="3"
              class="requiredFormItem"
              @blur="(e) => handleChange(e.target.value, record, col)"
            />
            <BaseInputNumber
              v-else
              v-model="record[col]"
              :precision="3"
              :disabled="
                col === 'number' ||
                col === 'lastSize' ||
                col === 'contractPrice' ||
                col === 'taxAmount' ||
                col === 'includeTaxAmount' ||
                col === 'includeTaxTotalAmount'
              "
              @blur="(e) => handleChange(e.target.value, record, col)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </b-table>
    <material-list-and-dir
      ref="detailDialog"
      :api="materialsDialogList"
      :request-params="{ contractId: row.contractId }"
      mode="single"
      @createList="createList"
    />
  </div>
</template>
<script>
import {
  materialsAddBatch,
  materialsDialogList,
  materialsEdit,
  materialsList,
  materialsListDel
} from '@/api/material/acceptance/dosage'
import { columns } from '@/views/materials/acceptance/dosage/components/materials/insideModel'
import { selectOption } from '@/api/material/goods/goods'

export default {
  props: {
    state: {
      type: Number
    },
    row: {
      type: Object
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      columns: columns,
      materialsDialogList: materialsDialogList,
      delFunc: materialsListDel,
      loadData: (params) => materialsList(Object.assign(params, { usageConfirmationId: this.row.id })),
      rateArr: []
    }
  },
  created() {
    this.getRate()
  },
  methods: {
    async getRate() {
      let res = await selectOption({ type: 21 })
      if (res.code === 200) {
        this.rateArr = res.data
      }
    },
    async importFunc(e) {
      let newTable = []
      e.map((row) => {
        let temp = {}
        for (const rowKey in row) {
          let column = this.columns.find((columnRow) => columnRow.title === rowKey)
          if (column) {
            let dataIndex = column.dataIndex
            temp[dataIndex] = row[rowKey]
          }
        }
        temp.materialContractId = this.id
        temp.beneficialId = this.id
        newTable.push(temp)
      })
      // this.$console(newTable)
      this.loading = true
      let res = await materialsAddBatch(newTable)
      this.loading = false
      this.$notification.open({ message: '提示', duration: null, description: () => <pre>{res.message}</pre> })
      this.$refs.table.getData(null, true)
    },
    async openDialog() {
      let allData = []
      if (this.$refs.table.totalSize !== 0) {
        this.loading = true
        let res = await materialsList({
          pageSize: this.$refs.table.totalSize,
          pageNo: 1,
          usageConfirmationId: this.row.id
        })
        this.loading = false
        if (res.code === this.SUCCESS_CODE) {
          allData = res.data
        }
      }
      this.$refs.detailDialog.open(allData)
    },
    async createList(selectRows) {
      let params = []
      selectRows.map((selectRow) => {
        params.push({
          materialName: selectRow.name,
          materialCode: selectRow.code,
          materialModel: selectRow.specificationModel,
          materialUnit: selectRow.unitName,
          usageConfirmationId: this.row.id,
          number: '',
          lastSize: '',
          contractPrice: null,
          taxRatePercentId: null,
          taxAmount: null,
          includeTaxAmount: null,
          includeTaxTotalAmount: null,
          deliveryDate: null,
          quantity: '',
          remark: '',
          contractDetailsId: selectRow.contractDetailsId
        })
      })
      this.loading = true
      let res = await materialsAddBatch(params)
      if (res.code === 200) {
        this.$refs.table.getData(null, true)
      }
      this.loading = false
    },
    handleChange(val, target, col) {
      if (target['taxRatePercentId']) {
        col === 'taxRatePercentName' &&
          (target['taxRatePercentName'] = this.rateArr.find((item) => item.id === val)?.name)
        let res = this.rateArr.find((v) => v.id === target['taxRatePercentId'])
        if (res) {
          let temp = this.$clone(res)
          temp.name = temp.name.replace('%', '')
          target['taxAmount'] = (target['contractPrice'] * Number(temp.name)) / 100
          target['includeTaxAmount'] = target['contractPrice'] + target['taxAmount']
          target['includeTaxTotalAmount'] = target['number'] * target['includeTaxAmount']
        }
      }
      this.save(target)
    },
    async save(target) {
      let res = await materialsEdit(target)
      if (res.code !== 200) this.$noticeWarning(res.message)
    }
  }
}
</script>
